const fs = require('fs')
const path = require('path')
const axios = require('axios')

// 配置API请求
axios.defaults.baseURL = 'http://127.0.0.1:8023/yethan'
axios.defaults.headers.ytoken =
  'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTc0MDE5MDExN30.Xen-zRWhuYg0d4Znk8o56hk1SrnHUt2DebMiBqdCmBg'

// 动态路径处理器
async function processMenuPaths() {
  try {
    const res = await axios.get('/getMenu')
    return res.data.data
      .filter(({ component }) => !['Layout', 'SecondMain'].includes(component))
      .map(({ component }) => {
        const normalizedPath = component
          .replace('@/views/', '')
          .replace(/\/index$/, '')
          .replace(/^\//, '')
        return path.normalize(normalizedPath)
      })
  } catch (error) {
    console.error('菜单数据获取失败:', error.response?.data || error.message)
    return []
  }
}

// 视图生成器配置
const config = {
  baseDir: path.resolve(__dirname, './generateView'),
  maxDepth: 5, // 最大路径深度限制
  skipExisting: true // 跳过已存在的文件
}

// 智能路径生成器
async function generateViewStructure() {
  const menuPaths = await processMenuPaths()
  if (!menuPaths.length) {
    console.warn('未获取到有效菜单路径，生成终止')
    return
  }

  console.log('开始生成视图结构，共检测到 %d 个路径', menuPaths.length)

  for (const routePath of menuPaths) {
    const pathSegments = routePath.split(path.sep).filter(Boolean)

    if (pathSegments.length > config.maxDepth) {
      console.warn(
        '路径深度超出限制[%d]，已跳过: %s',
        config.maxDepth,
        routePath
      )
      continue
    }

    let currentPath = config.baseDir
    for (const [index, segment] of pathSegments.entries()) {
      currentPath = path.join(currentPath, segment)

      try {
        // 创建目录（如果不存在）
        if (!fs.existsSync(currentPath)) {
          fs.mkdirSync(currentPath, { recursive: true })
          console.log('创建目录: %s', currentPath)
        }

        // 在末级目录生成文件
        if (index === pathSegments.length - 1) {
          await generateViewFiles(currentPath, routePath)
        }
      } catch (error) {
        console.error('路径处理失败: %s - %s', currentPath, error.message)
        break
      }
    }
  }
}

// 文件生成器
async function generateViewFiles(dirPath, routePath) {
  const indexPath = path.join(dirPath, 'index.vue')
  const componentsDir = path.join(dirPath, 'components')
  const formDialogPath = path.join(componentsDir, 'formDialog.vue')

  // 生成index.vue
  if (!config.skipExisting || !fs.existsSync(indexPath)) {
    fs.writeFileSync(indexPath, await generateIndexTemplate(routePath))
    console.log('生成视图文件: %s', indexPath)
  }

  // 生成components目录
  if (!fs.existsSync(componentsDir)) {
    fs.mkdirSync(componentsDir)
    console.log('创建组件目录: %s', componentsDir)
  }

  // 生成formDialog组件
  if (!config.skipExisting || !fs.existsSync(formDialogPath)) {
    fs.writeFileSync(formDialogPath, generateFormDialogTemplate())
    console.log('生成表单组件: %s', formDialogPath)
  }
}

// 增强的index.vue模板生成
async function generateIndexTemplate(routePath) {
  const componentName = routePath.split(path.sep).pop()
  const apiPath = routePath.replace(/\//g, '-')
  const routeKey = routePath.replace(/\//g, '_')

  return `<template>
    <div class="app-container">
        <y-table ref="gridRef" v-bind="listOptions" @toolbar-button-click="handleToolbarClick">
            <template #xm_default="{ row }">
                <div class="text-blue-500">{{ row.name }}</div>
            </template>
        </y-table>
        <form-dialog ref="formDialogRef" :path="'${routePath}'"></form-dialog>
    </div>
</template>

<script>
// import { getTableData, deleteMethod } from '@/api/${apiPath}';  // 实际接口
import { getTableData, deleteMethod } from '@/api/table' // 测试接口

import formDialog from './components/formDialog';
import listMixin from '@/mixins/listMixin';

export default {
    components: { formDialog },
    mixins: [listMixin],
    data() {
        return {
            listOptions: {
                dataMethod: getTableData,
                exportConfig: {
                    fileName: '${componentName}导出',
                    module: '${routeKey}_EXPORT'
                },
                importConfig: {
                    module: '${routeKey}_IMPORT'
                },
                formOptions: {
                    items: [
                        {
                            field: 'keywords',
                            title: '搜索关键词',
                            itemRender: { name: 'VxeInput' }
                        }
                    ]
                },
                tableOptions: {
                    rowConfig: { keyField: 'id' },
                    toolbarConfig: {
                        buttons: [
                            { 
                                name: '新增', 
                                code: 'add', 
                                status: 'primary',
                                icon: 'vxe-icon-add'
                            },
                            { name: '导出', code: 'export' },
                            { name: '导入', code: 'import' }
                        ]
                    },
                    columns: [
                        { type: 'seq', width: 60 },
                        { field: 'name', title: '名称' },
                        {
                            title: '操作',
                            cellRender: {
                                name: 'buttons',
                                options: [
                                    { content: '编辑', name: 'edit' },
                                    { 
                                        content: '更多',
                                        dropdowns: [
                                            { content: '删除', name: 'delete' }
                                        ]
                                    }
                                ],
                                events: { click: this.handleOperationClick }
                            }
                        }
                    ]
                }
            }
        };
    },
    methods: {
        handleToolbarClick({ code }) {
            switch(code) {
                case 'add':
                    this.$refs.formDialogRef.open();
                    break;
                case 'export':
                    this.handleExport();
                    break;
                case 'import':
                    this.handleImport();
                    break;
            }
        },
        handleOperationClick({ name, row }) {
            // ...保持原有操作逻辑
        }
    }
};
</script>`
}

// 增强的formDialog模板生成
function generateFormDialogTemplate() {
  return `<template>
    <y-dialog :title="title" v-bind="dialogOptions" @ok="handleSubmit">
        <y-form ref="formRef" :options="formOptions" @submit="submit" class="p-4">
            <template #extra_buttons>
                <vxe-button status="warning" @click="handleReset">重置</vxe-button>
            </template>
        </y-form>
    </y-dialog>
</template>

<script>
import { cloneDeep } from '@/utils';
import request from '@/utils/request';

export default {
    props: {
        path: String
    },
    data() {
        return {
            keyId: 'id',
            dialogOptions: { 
                loading: false,
                width: 800
            },
            formOptions: {
                items: [
                    {
                        field: 'name',
                        title: '名称',
                        required: true,
                        itemRender: { 
                            name: 'VxeInput',
                            props: { placeholder: '请输入名称' }
                        }
                    },
                    {
                        field: 'type',
                        title: '类型',
                        itemRender: {
                            name: 'ZSelect',
                            props: { 
                                dictCode: 'common_type',
                                clearable: true
                            }
                        }
                    }
                ]
            },
            formData: {}
        };
    },
    computed: {
        title() {
            return this.formData[this.keyId] ? '修改' : '新增';
        },
        apiUrl() {
            return \`/\${this.path}/\${this.formData[this.keyId] ? 'edit' : 'add'}\`;
        }
    },
    methods: {
        open(data = {}) {
            this.formData = cloneDeep(data);
            this.$nextTick(() => {
                this.$refs.formRef.reset();
                this.$refs.formRef.setData(data);
                this.$refs.dialogRef.open();
            });
        },
        handleReset() {
            this.$refs.formRef.reset();
        },
        async submit(data) {
            this.dialogOptions.loading = true;
            try {
                await request.post(this.apiUrl, data);
                this.$emit('submitted');
                this.$message.success('操作成功');
                this.$refs.dialogRef.close();
            } finally {
                this.dialogOptions.loading = false;
            }
        }
    }
};
</script>`
}

// 启动生成流程
generateViewStructure()
  .then(() => console.log('视图生成完成'))
  .catch((err) => console.error('生成过程异常终止:', err))
